"""
AI Historical Simulation Platform - Web Interface

This module provides a comprehensive web-based interface including user chat,
administrative dashboard, real-time monitoring, and educational tools integration.
"""

import asyncio
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any
from dataclasses import asdict

try:
    from fastapi import FastAPI, Request, Form, Depends, HTTPException
    from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    from fastapi.middleware.cors import CORSMiddleware
    from fastapi.security import HTTPBasic, HTTPBasicCredentials
    import secrets
    FASTAPI_AVAILABLE = True
except ImportError:
    FASTAPI_AVAILABLE = False

from .api_server import APIServer

logger = logging.getLogger(__name__)


class WebInterface:
    """
    Comprehensive web interface for the AI Historical Simulation Platform.
    
    Features:
    - Interactive chat interface with historical figures
    - Administrative dashboard with system monitoring
    - Real-time performance metrics and alerts
    - Educational tools and scenario management
    - Multi-user session management interface
    """
    
    def __init__(self, platform, api_server: APIServer):
        """
        Initialize web interface.
        
        Args:
            platform: AI Historical Simulation Platform instance
            api_server: API server instance for backend communication
        """
        if not FASTAPI_AVAILABLE:
            raise ImportError("FastAPI not available. Install with: pip install fastapi uvicorn jinja2")
        
        self.platform = platform
        self.api_server = api_server
        
        # Setup directories
        self.web_dir = Path(__file__).parent / "web"
        self.templates_dir = self.web_dir / "templates"
        self.static_dir = self.web_dir / "static"
        
        self._ensure_directories()
        
        # Initialize templates
        self.templates = Jinja2Templates(directory=str(self.templates_dir))
        
        # Simple authentication (in production, use proper auth)
        self.security = HTTPBasic()
        self.admin_credentials = {
            "admin": "admin123",  # Change in production
            "educator": "edu123",
            "researcher": "research123"
        }
        
        # Create web application
        self.app = self._create_web_app()
        
        # Create default templates and static files
        self._create_default_templates()
        self._create_default_static_files()
        
        logger.info("WebInterface initialized")
    
    def _ensure_directories(self) -> None:
        """Ensure web directories exist."""
        self.web_dir.mkdir(exist_ok=True)
        self.templates_dir.mkdir(exist_ok=True)
        self.static_dir.mkdir(exist_ok=True)
        (self.static_dir / "js").mkdir(exist_ok=True)
        (self.static_dir / "css").mkdir(exist_ok=True)
        (self.static_dir / "images").mkdir(exist_ok=True)
    
    def _create_web_app(self) -> FastAPI:
        """Create FastAPI web application."""
        app = FastAPI(
            title="AI Historical Simulation Platform - Web Interface",
            description="Web interface for interacting with historical figures",
            version="1.0.0",
            docs_url=None,  # Disable docs for web interface
            redoc_url=None
        )
        
        # Add CORS middleware
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
        
        # Mount static files
        app.mount("/static", StaticFiles(directory=str(self.static_dir)), name="static")
        
        # Store references
        app.state.platform = self.platform
        app.state.api_server = self.api_server
        app.state.web_interface = self
        
        # Setup routes
        self._setup_routes(app)
        
        return app
    
    def _setup_routes(self, app: FastAPI) -> None:
        """Setup web interface routes."""
        
        def get_current_user(credentials: HTTPBasicCredentials = Depends(self.security)):
            """Authentication dependency."""
            username = credentials.username
            password = credentials.password
            
            if username in self.admin_credentials and self.admin_credentials[username] == password:
                return username
            
            raise HTTPException(
                status_code=401,
                detail="Invalid credentials",
                headers={"WWW-Authenticate": "Basic"},
            )
        
        # Main chat interface
        @app.get("/", response_class=HTMLResponse)
        async def home(request: Request):
            """Main chat interface."""
            figures = list(self.platform.historical_figures.keys())
            if not figures:
                # Load some default figures for demo
                try:
                    await self.platform.load_historical_figure("Napoleon Bonaparte")
                    await self.platform.load_historical_figure("William Shakespeare")
                    await self.platform.load_historical_figure("Albert Einstein")
                    figures = list(self.platform.historical_figures.keys())
                except Exception as e:
                    logger.warning(f"Failed to load default figures: {e}")
            
            return self.templates.TemplateResponse(
                "chat.html",
                {
                    "request": request,
                    "figures": figures,
                    "api_key": self.api_server.get_admin_api_key()
                }
            )
        
        # Dashboard interface (requires authentication)
        @app.get("/dashboard", response_class=HTMLResponse)
        async def dashboard(request: Request, user: str = Depends(get_current_user)):
            """Administrative dashboard."""
            return self.templates.TemplateResponse(
                "dashboard.html",
                {
                    "request": request,
                    "user": user,
                    "api_key": self.api_server.get_admin_api_key()
                }
            )
        
        # System monitoring interface
        @app.get("/monitor", response_class=HTMLResponse)
        async def monitor(request: Request, user: str = Depends(get_current_user)):
            """Real-time system monitoring."""
            return self.templates.TemplateResponse(
                "monitor.html",
                {
                    "request": request,
                    "user": user,
                    "api_key": self.api_server.get_admin_api_key()
                }
            )
        
        # Educational tools interface
        @app.get("/scenarios", response_class=HTMLResponse)
        async def scenarios(request: Request, user: str = Depends(get_current_user)):
            """Educational scenarios management."""
            return self.templates.TemplateResponse(
                "scenarios.html",
                {
                    "request": request,
                    "user": user,
                    "api_key": self.api_server.get_admin_api_key()
                }
            )
        
        # Session management interface
        @app.get("/sessions", response_class=HTMLResponse)
        async def sessions_management(request: Request, user: str = Depends(get_current_user)):
            """Session management interface."""
            return self.templates.TemplateResponse(
                "sessions.html",
                {
                    "request": request,
                    "user": user,
                    "api_key": self.api_server.get_admin_api_key()
                }
            )
        
        # Figure management interface
        @app.get("/figures", response_class=HTMLResponse)
        async def figures_management(request: Request, user: str = Depends(get_current_user)):
            """Historical figures management."""
            return self.templates.TemplateResponse(
                "figures.html",
                {
                    "request": request,
                    "user": user,
                    "api_key": self.api_server.get_admin_api_key(),
                    "figures": list(self.platform.historical_figures.keys())
                }
            )
        
        # API endpoints for web interface
        @app.get("/api/web/health")
        async def web_health():
            """Health check for web interface."""
            try:
                health = await self.platform.get_platform_health()
                return {"status": "ok", "health": asdict(health)}
            except Exception as e:
                return JSONResponse(
                    status_code=500,
                    content={"status": "error", "error": str(e)}
                )
        
        @app.get("/api/web/metrics")
        async def web_metrics():
            """Get metrics for web dashboard."""
            try:
                metrics = await self.platform.get_system_metrics()
                return {"metrics": metrics}
            except Exception as e:
                return JSONResponse(
                    status_code=500,
                    content={"error": str(e)}
                )
        
        @app.get("/api/web/sessions")
        async def web_sessions():
            """Get session information for web interface."""
            try:
                session_ids = await self.platform.session_manager.get_active_sessions()
                sessions = []
                
                for session_id in session_ids[:50]:  # Limit to first 50
                    session = await self.platform.session_manager.get_session(session_id)
                    if session:
                        sessions.append(session.to_dict())
                
                return {"sessions": sessions}
            except Exception as e:
                return JSONResponse(
                    status_code=500,
                    content={"error": str(e)}
                )
        
        @app.post("/api/web/figures/{figure_name}/load")
        async def web_load_figure(figure_name: str):
            """Load a historical figure via web interface."""
            try:
                figure = await self.platform.load_historical_figure(figure_name, force_reload=True)
                return {"status": "loaded", "figure": figure.to_dict()}
            except Exception as e:
                return JSONResponse(
                    status_code=400,
                    content={"error": str(e)}
                )
    
    def _create_default_templates(self) -> None:
        """Create default HTML templates."""
        
        # Base template
        base_template = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}AI Historical Simulation Platform{% endblock %}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-clock-history"></i>
                Historical Simulation Platform
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/">Chat</a>
                <a class="nav-link" href="/dashboard">Dashboard</a>
                <a class="nav-link" href="/monitor">Monitor</a>
                <a class="nav-link" href="/scenarios">Scenarios</a>
            </div>
        </div>
    </nav>
    
    <main class="container-fluid mt-3">
        {% block content %}{% endblock %}
    </main>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="/static/js/common.js"></script>
    {% block scripts %}{% endblock %}
</body>
</html>"""
        
        (self.templates_dir / "base.html").write_text(base_template)
        
        # Chat interface template
        chat_template = """{% extends "base.html" %}

{% block title %}Chat - AI Historical Simulation Platform{% endblock %}

{% block content %}
<div class="row h-100">
    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <h5><i class="bi bi-people"></i> Historical Figures</h5>
            </div>
            <div class="card-body">
                <div id="figures-list">
                    {% for figure in figures %}
                    <button class="btn btn-outline-primary btn-sm mb-2 w-100 figure-btn" 
                            data-figure="{{ figure }}" onclick="selectFigure('{{ figure }}')">
                        {{ figure }}
                    </button>
                    {% endfor %}
                </div>
                <hr>
                <div class="mt-3">
                    <button class="btn btn-success btn-sm w-100" onclick="startCrossTemporalChat()">
                        <i class="bi bi-chat-dots"></i> Cross-Temporal Chat
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-9">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 id="current-figure">
                    <i class="bi bi-chat-square-text"></i>
                    Select a Historical Figure
                </h5>
                <div>
                    <button class="btn btn-sm btn-outline-secondary" onclick="exportChat()">
                        <i class="bi bi-download"></i> Export
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="clearChat()">
                        <i class="bi bi-trash"></i> Clear
                    </button>
                </div>
            </div>
            <div class="card-body d-flex flex-column">
                <div id="chat-messages" class="flex-grow-1 overflow-auto mb-3" style="height: 500px;">
                    <div class="text-center text-muted p-4">
                        <i class="bi bi-chat-quote display-4 d-block mb-3"></i>
                        <h5>Welcome to the AI Historical Simulation Platform!</h5>
                        <p>Select a historical figure to begin your conversation across time.</p>
                        <small class="text-muted">
                            Experience authentic dialogue powered by advanced AI personality modeling.
                        </small>
                    </div>
                </div>
                
                <div class="input-group">
                    <input type="text" id="message-input" class="form-control" 
                           placeholder="Ask about their life, thoughts, or historical events..." disabled>
                    <button class="btn btn-primary" id="send-button" onclick="sendMessage()" disabled>
                        <i class="bi bi-send"></i> Send
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Connection Status -->
<div id="connection-status" class="position-fixed bottom-0 end-0 m-3">
    <span class="badge bg-secondary">Connecting...</span>
</div>

<!-- Cross-Temporal Chat Modal -->
<div class="modal fade" id="crossTemporalModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Cross-Temporal Conversation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Select Figures:</h6>
                        <div id="figure-selection">
                            {% for figure in figures %}
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="fig_{{ loop.index }}" value="{{ figure }}">
                                <label class="form-check-label" for="fig_{{ loop.index }}">{{ figure }}</label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="conversation-topic" class="form-label">Discussion Topic:</label>
                            <input type="text" class="form-control" id="conversation-topic" 
                                   placeholder="e.g., The nature of leadership">
                        </div>
                        <div class="mb-3">
                            <label for="conversation-rounds" class="form-label">Rounds:</label>
                            <select class="form-select" id="conversation-rounds">
                                <option value="2">2 rounds</option>
                                <option value="3" selected>3 rounds</option>
                                <option value="4">4 rounds</option>
                                <option value="5">5 rounds</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="startCrossTemporalConversation()">Start Conversation</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    const API_KEY = "{{ api_key }}";
    let ws = null;
    let currentFigure = null;
    let sessionId = null;
    let connectionId = "web_" + Date.now() + "_" + Math.random();
    
    // Initialize WebSocket connection
    function initWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        ws = new WebSocket(`${protocol}//${window.location.host}/ws/${connectionId}`);
        
        ws.onopen = function() {
            updateConnectionStatus('Connected', 'success');
            
            // Authenticate
            ws.send(JSON.stringify({
                type: 'auth',
                api_key: API_KEY
            }));
        };
        
        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            handleWebSocketMessage(data);
        };
        
        ws.onclose = function() {
            updateConnectionStatus('Disconnected', 'danger');
            // Attempt reconnection after 3 seconds
            setTimeout(initWebSocket, 3000);
        };
        
        ws.onerror = function(error) {
            console.error('WebSocket error:', error);
            updateConnectionStatus('Error', 'warning');
        };
    }
    
    function handleWebSocketMessage(data) {
        switch(data.type) {
            case 'auth_success':
                console.log('WebSocket authenticated');
                break;
            case 'chat_response':
                displayMessage(data.figure, data.response, false);
                break;
            case 'error':
                showAlert(data.message, 'danger');
                break;
        }
    }
    
    function selectFigure(figureName) {
        currentFigure = figureName;
        document.getElementById('current-figure').innerHTML = 
            `<i class="bi bi-person-circle"></i> ${figureName}`;
        
        // Enable input
        document.getElementById('message-input').disabled = false;
        document.getElementById('send-button').disabled = false;
        
        // Highlight selected figure
        document.querySelectorAll('.figure-btn').forEach(btn => {
            btn.classList.remove('btn-primary');
            btn.classList.add('btn-outline-primary');
        });
        
        document.querySelector(`[data-figure="${figureName}"]`).classList.remove('btn-outline-primary');
        document.querySelector(`[data-figure="${figureName}"]`).classList.add('btn-primary');
        
        // Clear and show welcome message
        document.getElementById('chat-messages').innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i>
                You are now conversing with <strong>${figureName}</strong>. 
                Ask about their life, thoughts, or historical perspectives!
            </div>
        `;
        
        document.getElementById('message-input').focus();
    }
    
    async function sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        
        if (!message || !currentFigure) return;
        
        // Display user message
        displayMessage('You', message, true);
        
        // Clear input
        input.value = '';
        
        try {
            const response = await fetch('/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    figure_name: currentFigure,
                    message: message,
                    session_id: sessionId
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                sessionId = data.session_id;
                displayMessage(currentFigure, data.response, false);
                
                // Show response time if > 100ms
                if (data.response_time_ms > 100) {
                    console.log(`Response time: ${data.response_time_ms.toFixed(1)}ms`);
                }
            } else {
                throw new Error(data.detail || 'Request failed');
            }
            
        } catch (error) {
            showAlert(`Error: ${error.message}`, 'danger');
        }
    }
    
    function displayMessage(sender, message, isUser = false) {
        const chatMessages = document.getElementById('chat-messages');
        const messageDiv = document.createElement('div');
        messageDiv.className = `d-flex mb-3 ${isUser ? 'justify-content-end' : 'justify-content-start'}`;
        
        const bubbleClass = isUser ? 'bg-primary text-white' : 'bg-light border';
        const icon = isUser ? 'bi-person-circle' : 'bi-person-badge';
        
        messageDiv.innerHTML = `
            <div class="message-bubble p-3 rounded ${bubbleClass}" style="max-width: 70%;">
                <div class="d-flex align-items-center mb-2">
                    <i class="bi ${icon} me-2"></i>
                    <strong>${sender}</strong>
                    <small class="ms-auto text-muted">${new Date().toLocaleTimeString()}</small>
                </div>
                <div>${message}</div>
            </div>
        `;
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    function clearChat() {
        document.getElementById('chat-messages').innerHTML = `
            <div class="text-center text-muted">
                <i class="bi bi-trash"></i> Chat cleared
            </div>
        `;
    }
    
    function exportChat() {
        const messages = document.getElementById('chat-messages');
        const chatContent = messages.innerText;
        
        const blob = new Blob([chatContent], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `chat_${currentFigure || 'conversation'}_${new Date().toISOString().split('T')[0]}.txt`;
        a.click();
        URL.revokeObjectURL(url);
    }
    
    function startCrossTemporalChat() {
        const modal = new bootstrap.Modal(document.getElementById('crossTemporalModal'));
        modal.show();
    }
    
    async function startCrossTemporalConversation() {
        const selectedFigures = Array.from(document.querySelectorAll('#figure-selection input:checked'))
            .map(cb => cb.value);
        const topic = document.getElementById('conversation-topic').value.trim();
        const rounds = parseInt(document.getElementById('conversation-rounds').value);
        
        if (selectedFigures.length < 2) {
            showAlert('Please select at least 2 figures', 'warning');
            return;
        }
        
        if (!topic) {
            showAlert('Please enter a discussion topic', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/conversations/cross-temporal', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    figure_names: selectedFigures,
                    topic: topic,
                    rounds: rounds,
                    session_id: sessionId
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                bootstrap.Modal.getInstance(document.getElementById('crossTemporalModal')).hide();
                displayCrossTemporalConversation(data.conversation);
            } else {
                throw new Error(data.detail || 'Request failed');
            }
            
        } catch (error) {
            showAlert(`Error: ${error.message}`, 'danger');
        }
    }
    
    function displayCrossTemporalConversation(conversation) {
        const chatMessages = document.getElementById('chat-messages');
        chatMessages.innerHTML = `
            <div class="alert alert-success">
                <i class="bi bi-chat-dots"></i>
                <strong>Cross-Temporal Conversation Started</strong>
            </div>
        `;
        
        conversation.forEach(exchange => {
            displayMessage(
                `${exchange.figure} (${exchange.historical_period})`,
                exchange.response,
                false
            );
        });
    }
    
    function updateConnectionStatus(status, type) {
        const statusElement = document.getElementById('connection-status');
        statusElement.innerHTML = `<span class="badge bg-${type}">${status}</span>`;
    }
    
    function showAlert(message, type = 'info') {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 400px;';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        initWebSocket();
        
        // Handle Enter key in message input
        document.getElementById('message-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    });
</script>
{% endblock %}"""
        
        (self.templates_dir / "chat.html").write_text(chat_template)
        
        # Dashboard template (simplified version)
        dashboard_template = """{% extends "base.html" %}

{% block title %}Dashboard - AI Historical Simulation Platform{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12 mb-4">
        <h2><i class="bi bi-speedometer2"></i> System Dashboard</h2>
        <p class="text-muted">Real-time monitoring of the AI Historical Simulation Platform</p>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-center bg-primary text-white">
            <div class="card-body">
                <i class="bi bi-people display-4"></i>
                <h5 class="card-title">Active Sessions</h5>
                <h2 id="active-sessions">-</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center bg-success text-white">
            <div class="card-body">
                <i class="bi bi-chat-dots display-4"></i>
                <h5 class="card-title">Total Messages</h5>
                <h2 id="total-messages">-</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center bg-info text-white">
            <div class="card-body">
                <i class="bi bi-person-badge display-4"></i>
                <h5 class="card-title">Loaded Figures</h5>
                <h2 id="loaded-figures">-</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center bg-warning text-white">
            <div class="card-body">
                <i class="bi bi-stopwatch display-4"></i>
                <h5 class="card-title">Avg Response Time</h5>
                <h2 id="avg-response-time">-</h2>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5><i class="bi bi-graph-up"></i> Performance Metrics</h5>
            </div>
            <div class="card-body">
                <canvas id="metricsChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5><i class="bi bi-heart-pulse"></i> System Health</h5>
            </div>
            <div class="card-body">
                <div id="health-status">
                    <div class="text-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    const API_KEY = "{{ api_key }}";
    let metricsChart = null;
    
    async function loadDashboardData() {
        try {
            const response = await fetch('/api/web/metrics');
            const data = await response.json();
            
            if (response.ok) {
                updateMetricsDisplay(data.metrics);
                updateHealthDisplay(data.metrics.health);
            } else {
                console.error('Failed to load metrics:', data.error);
            }
        } catch (error) {
            console.error('Error loading dashboard data:', error);
        }
    }
    
    function updateMetricsDisplay(metrics) {
        document.getElementById('active-sessions').textContent = 
            metrics.sessions?.active_sessions || 0;
        document.getElementById('total-messages').textContent = 
            metrics.sessions?.total_messages || 0;
        document.getElementById('loaded-figures').textContent = 
            metrics.figures?.loaded || 0;
        document.getElementById('avg-response-time').textContent = 
            `${(metrics.performance?.avg_response_time || 0).toFixed(0)}ms`;
    }
    
    function updateHealthDisplay(health) {
        const healthDiv = document.getElementById('health-status');
        const isHealthy = health?.is_healthy;
        
        healthDiv.innerHTML = `
            <div class="text-center">
                <i class="bi bi-${isHealthy ? 'check-circle text-success' : 'exclamation-triangle text-warning'} display-4"></i>
                <h4 class="mt-2">${isHealthy ? 'Healthy' : 'Warning'}</h4>
                <p class="text-muted">
                    Uptime: ${Math.round(health?.uptime_seconds || 0)}s<br>
                    Memory: ${(health?.memory_usage_mb || 0).toFixed(1)}MB
                </p>
            </div>
        `;
    }
    
    function initializeChart() {
        const ctx = document.getElementById('metricsChart').getContext('2d');
        metricsChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'Response Time (ms)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    // Initialize dashboard
    document.addEventListener('DOMContentLoaded', function() {
        initializeChart();
        loadDashboardData();
        
        // Auto-refresh every 30 seconds
        setInterval(loadDashboardData, 30000);
    });
</script>
{% endblock %}"""
        
        (self.templates_dir / "dashboard.html").write_text(dashboard_template)
        
        # Create other templates (monitor, scenarios, sessions, figures)
        self._create_additional_templates()
    
    def _create_additional_templates(self) -> None:
        """Create additional template files."""
        
        # Monitor template
        monitor_template = """{% extends "base.html" %}
{% block title %}Monitor - AI Historical Simulation Platform{% endblock %}
{% block content %}
<h2><i class="bi bi-display"></i> Real-time Monitoring</h2>
<div class="alert alert-info">Real-time system monitoring interface - Advanced metrics and alerts</div>
{% endblock %}"""
        
        # Scenarios template  
        scenarios_template = """{% extends "base.html" %}
{% block title %}Scenarios - AI Historical Simulation Platform{% endblock %}
{% block content %}
<h2><i class="bi bi-book"></i> Educational Scenarios</h2>
<div class="alert alert-info">Educational scenario management and tools for teachers and researchers</div>
{% endblock %}"""
        
        # Sessions template
        sessions_template = """{% extends "base.html" %}
{% block title %}Sessions - AI Historical Simulation Platform{% endblock %}
{% block content %}
<h2><i class="bi bi-activity"></i> Session Management</h2>
<div id="sessions-list">Loading sessions...</div>
{% endblock %}
{% block scripts %}
<script>
async function loadSessions() {
    try {
        const response = await fetch('/api/web/sessions');
        const data = await response.json();
        const sessionsList = document.getElementById('sessions-list');
        
        if (data.sessions && data.sessions.length > 0) {
            sessionsList.innerHTML = data.sessions.map(session => `
                <div class="card mb-2">
                    <div class="card-body">
                        <h6>Session: ${session.session_id}</h6>
                        <p>User: ${session.user_id || 'Anonymous'}<br>
                           Messages: ${session.total_messages}<br>
                           Active Figure: ${session.active_figure || 'None'}</p>
                    </div>
                </div>
            `).join('');
        } else {
            sessionsList.innerHTML = '<div class="alert alert-info">No active sessions</div>';
        }
    } catch (error) {
        document.getElementById('sessions-list').innerHTML = 
            '<div class="alert alert-danger">Error loading sessions</div>';
    }
}
document.addEventListener('DOMContentLoaded', loadSessions);
</script>
{% endblock %}"""
        
        # Figures template
        figures_template = """{% extends "base.html" %}
{% block title %}Figures - AI Historical Simulation Platform{% endblock %}
{% block content %}
<h2><i class="bi bi-person-lines-fill"></i> Historical Figures Management</h2>
<div class="row">
    {% for figure in figures %}
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body">
                <h5>{{ figure }}</h5>
                <button class="btn btn-primary btn-sm" onclick="reloadFigure('{{ figure }}')">Reload</button>
            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}
{% block scripts %}
<script>
async function reloadFigure(figureName) {
    try {
        const response = await fetch(`/api/web/figures/${figureName}/load`, {method: 'POST'});
        const data = await response.json();
        if (response.ok) {
            alert(`${figureName} reloaded successfully`);
        } else {
            alert(`Error: ${data.error}`);
        }
    } catch (error) {
        alert(`Error reloading figure: ${error.message}`);
    }
}
</script>
{% endblock %}"""
        
        (self.templates_dir / "monitor.html").write_text(monitor_template)
        (self.templates_dir / "scenarios.html").write_text(scenarios_template)
        (self.templates_dir / "sessions.html").write_text(sessions_template)
        (self.templates_dir / "figures.html").write_text(figures_template)
    
    def _create_default_static_files(self) -> None:
        """Create default static files (CSS, JS)."""
        
        # CSS file
        css_content = """
/* AI Historical Simulation Platform - Web Interface Styles */

body {
    background-color: #f8f9fa;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.navbar-brand {
    font-weight: bold;
    font-size: 1.25rem;
}

.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border: 1px solid rgba(0, 0, 0, 0.125);
    transition: all 0.2s ease-in-out;
}

.card:hover {
    box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
}

.message-bubble {
    word-wrap: break-word;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

#chat-messages {
    background-color: white;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    padding: 1rem;
}

#connection-status {
    z-index: 1000;
}

.figure-btn {
    transition: all 0.2s ease-in-out;
}

.figure-btn:hover {
    transform: translateY(-1px);
}

.btn:focus {
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.alert {
    border: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.display-4 {
    font-size: 2.5rem;
}

@media (max-width: 768px) {
    .container-fluid {
        padding: 0.5rem;
    }
    
    .card {
        margin-bottom: 1rem;
    }
}

/* Animation for message appearance */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-bubble {
    animation: fadeInUp 0.3s ease-out;
}

/* Loading spinner */
.spinner-border-sm {
    width: 1rem;
    height: 1rem;
}
"""
        
        (self.static_dir / "css" / "style.css").write_text(css_content)
        
        # JavaScript file
        js_content = """
// AI Historical Simulation Platform - Common JavaScript Functions

// Utility functions
function formatTimestamp(timestamp) {
    return new Date(timestamp).toLocaleString();
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Toast notifications
function showToast(message, type = 'info', duration = 5000) {
    const toastContainer = getOrCreateToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${escapeHtml(message)}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" 
                    data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast, { autohide: true, delay: duration });
    bsToast.show();
    
    // Remove element after hiding
    toast.addEventListener('hidden.bs.toast', () => toast.remove());
}

function getOrCreateToastContainer() {
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
    }
    return container;
}

// Loading states
function showLoading(elementId, message = 'Loading...') {
    const element = document.getElementById(elementId);
    if (element) {
        element.innerHTML = `
            <div class="text-center p-3">
                <div class="spinner-border spinner-border-sm me-2" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                ${message}
            </div>
        `;
    }
}

function hideLoading(elementId, content) {
    const element = document.getElementById(elementId);
    if (element) {
        element.innerHTML = content;
    }
}

// Error handling
function handleApiError(error, defaultMessage = 'An error occurred') {
    console.error('API Error:', error);
    
    let message = defaultMessage;
    if (error.response && error.response.data && error.response.data.detail) {
        message = error.response.data.detail;
    } else if (error.message) {
        message = error.message;
    }
    
    showToast(message, 'danger');
}

// Local storage helpers
function saveToLocalStorage(key, data) {
    try {
        localStorage.setItem(key, JSON.stringify(data));
    } catch (error) {
        console.warn('Failed to save to localStorage:', error);
    }
}

function loadFromLocalStorage(key, defaultValue = null) {
    try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
        console.warn('Failed to load from localStorage:', error);
        return defaultValue;
    }
}

// Theme management
function setTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    saveToLocalStorage('theme', theme);
}

function getTheme() {
    return loadFromLocalStorage('theme', 'light');
}

// Initialize theme on page load
document.addEventListener('DOMContentLoaded', function() {
    const theme = getTheme();
    if (theme !== 'light') {
        setTheme(theme);
    }
});

// Common event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Add click handlers for copy buttons
    document.querySelectorAll('[data-copy-text]').forEach(button => {
        button.addEventListener('click', function() {
            const text = this.getAttribute('data-copy-text');
            navigator.clipboard.writeText(text).then(() => {
                showToast('Copied to clipboard!', 'success', 2000);
            }).catch(err => {
                console.error('Failed to copy text:', err);
                showToast('Failed to copy text', 'danger');
            });
        });
    });
    
    // Add handlers for external links
    document.querySelectorAll('a[href^="http"]').forEach(link => {
        link.setAttribute('target', '_blank');
        link.setAttribute('rel', 'noopener noreferrer');
    });
});
"""
        
        (self.static_dir / "js" / "common.js").write_text(js_content)
        
        logger.info("Created default static files")
    
    def get_app(self) -> FastAPI:
        """Get the FastAPI web application."""
        return self.app